"""
统一聊天接口
"""

from typing import Any, Dict, Generator, List, Optional, Union

from .clients.base_client import ChatResponse
from .clients.factory import create_client
from .logging import setup_logger

logger = setup_logger(__name__)


def chat_with_model(
        model_name: str,
        messages: List[Dict[str, Any]],
        stream: bool = False) -> Union[str, Generator[str, None, None], None]:
    """
    与模型进行对话
    
    Args:
        model_name: 模型名称
        messages: 对话消息列表
        stream: 是否使用流式输出
        
    Returns:
        如果stream=False，返回字符串响应或None（出错时）
        如果stream=True，返回字符串生成器
    """
    try:
        client = create_client(model_name)

        if stream:
            # 返回生成器对象
            return client.chat_stream(messages)
        else:
            response = client.chat(messages)
            if isinstance(response, ChatResponse):
                if response.status:
                    return response.content
                else:
                    logger.error(f"Chat failed: {response.error_msg}")
                    return None
            else:
                # 处理直接返回字符串的情况
                return response
    except Exception as e:
        logger.error(f"Error in chat_with_model: {e}")
        return None
